package com.iotmonitor.iot.service.impl;

import java.util.List;
import java.util.Map;

import com.google.common.collect.Lists;
import com.iotmonitor.iot.es.ESRepository;
import com.iotmonitor.iot.service.ITbGpsService;
import com.iotmonitor.iot.service.ITbQuotaService;
import com.iotmonitor.iot.domain.TbGps;
import com.iotmonitor.iot.domain.dto.DeviceDTO;
import com.iotmonitor.iot.domain.dto.DeviceFullInfo;
import com.iotmonitor.iot.domain.dto.DeviceLocation;
import com.iotmonitor.iot.domain.dto.QuotaInfo;
import com.iotmonitor.iot.emq.EmqClient;
import com.iotmonitor.iot.mapper.TbGpsMapper;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.elasticsearch.common.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * GPS配置Service业务层处理
 *
 * @author ruoyi
 * @date 2023-08-11
 */
@Service
public class TbGpsServiceImpl implements ITbGpsService {
    @Autowired
    private TbGpsMapper tbGpsMapper;

    @Autowired
    private ESRepository esRepository;

    @Autowired
    private ITbQuotaService quotaService;

    @Autowired
    private EmqClient emqClient;

    /**
     * 查询GPS配置
     *
     * @param id GPS配置主键
     * @return GPS配置
     */
    @Override
    public TbGps selectTbGpsById(Long id) {
        return tbGpsMapper.selectTbGpsById(id);
    }

    /**
     * 查询GPS配置列表
     *
     * @param tbGps GPS配置
     * @return GPS配置
     */
    @Override
    public List<TbGps> selectTbGpsList(TbGps tbGps) {
        return tbGpsMapper.selectTbGpsList(tbGps);
    }

    /**
     * 新增GPS配置
     *
     * @param tbGps GPS配置
     * @return 结果
     */
    @Override
    public int insertTbGps(TbGps tbGps) {
        return tbGpsMapper.insertTbGps(tbGps);
    }

    /**
     * 修改GPS配置
     *
     * @param tbGps GPS配置
     * @return 结果
     */
    @Override
    public int updateTbGps(TbGps tbGps) {
        try {
            emqClient.subscribe("$queue/" + tbGps.getSubject());
            System.out.println("订阅gps主题：" + tbGps.getSubject());
        } catch (MqttException e) {
            e.printStackTrace();
        }

        tbGps.setId(1L);
        return tbGpsMapper.updateTbGps(tbGps);
    }

    /**
     * 批量删除GPS配置
     *
     * @param ids 需要删除的GPS配置主键
     * @return 结果
     */
    @Override
    public int deleteTbGpsByIds(Long[] ids) {
        return tbGpsMapper.deleteTbGpsByIds(ids);
    }

    /**
     * 删除GPS配置信息
     *
     * @param id GPS配置主键
     * @return 结果
     */
    @Override
    public int deleteTbGpsById(Long id) {
        return tbGpsMapper.deleteTbGpsById(id);
    }

    @Override
    public List<DeviceFullInfo> getDeviceFullInfo(Double lat, Double lon, Integer distance) {
        // 按范围查询设备
        List<DeviceLocation> deviceLocationList = esRepository.searchDeviceLocation(lat, lon, distance);

        List<DeviceFullInfo> deviceFullInfoList = Lists.newArrayList();

        // 查询设备详情
        deviceLocationList.forEach(deviceLocation -> {
            DeviceFullInfo deviceFullInfo = new DeviceFullInfo();
            deviceFullInfo.setDeviceId(deviceLocation.getDeviceId());// 设备id
            deviceFullInfo.setLocation(deviceLocation.getLocation());// 坐标

            // 在线状态和告警状态

            DeviceDTO deviceDTO = esRepository.searchDeviceById(deviceLocation.getDeviceId());
            if (deviceDTO == null) {
                deviceFullInfo.setOnline(false);
                deviceFullInfo.setAlarm(false);
            } else {
                deviceFullInfo.setOnline(deviceDTO.getOnline());
                deviceFullInfo.setAlarm(deviceDTO.getAlarm());
            }

            // 指标
            List<QuotaInfo> quotaList = quotaService.getLastQuotaList(deviceLocation.getDeviceId());
            deviceFullInfo.setQuotaList(quotaList);
            deviceFullInfoList.add(deviceFullInfo);
        });


        return deviceFullInfoList;
    }

    @Override
    public TbGps getGps() {
        return tbGpsMapper.selectTbGpsById(1L);
    }

    @Override
    public DeviceLocation analysis(String topic, Map<String, Object> payloadMap) {

        // 读取规则，规则为空不分析
        TbGps gpsEntity = getGps();
        if (gpsEntity == null) {
            return null;
        }
        // 订阅主题为空不分析
        if (Strings.isNullOrEmpty(gpsEntity.getSubject())) {
            return null;
        }
        // 订阅主题非geo不分析
        if (!topic.equals(gpsEntity.getSubject())) {
            return null;
        }

        // 读取设备id
        String deviceId = (String) payloadMap.get(gpsEntity.getSnKey());
        if (Strings.isNullOrEmpty(deviceId)) {
            return null;
        }

        // 提取gps
        String location = null;
        if (gpsEntity.getSingleField()) {// 单字段 （gps是从一个属性中传过来  经度,纬度 ）
            String gps = (String) payloadMap.get(gpsEntity.getValueKey());
            String[] split = gps.split(gpsEntity.getSeparation());
            if (split.length == 2) {
                location = split[1] + "," + split[0]; // 纬度，经度
            }
        } else {// 如果是双字段
            String lat = (String) payloadMap.get(gpsEntity.getLatitude());// 纬度
            String lon = (String) payloadMap.get(gpsEntity.getLongitude());// 经度
            if (!Strings.isNullOrEmpty(lat) && !Strings.isNullOrEmpty(lon)) {
                location = lat + "," + lon;
            }
        }
        if (location == null) {
            return null;
        }

        // 封装返回数据
        DeviceLocation deviceLocation = new DeviceLocation();
        deviceLocation.setDeviceId(deviceId);
        deviceLocation.setLocation(location);

        return deviceLocation;
    }
}
